#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root)
    {
        if (root == nullptr)
        {
            return true;
        }

        int left = treeHigh(root->left);
        int right = treeHigh(root->right);

        if (abs(right - left) > 1)
        {
            return false;
        }

        return isBalanced(root->left) && isBalanced(root->right);
    }

    int treeHigh(TreeNode* root)
    {
        if (nullptr == root)
        {
            return 0;
        }

        int left = treeHigh(root->left);
        int right = treeHigh(root->right);

        return 1 + std::max(left, right);
    }
};